//
//  HttpRequest.swift
//  swift-h5
//
//  Created by emma on 2023/12/25.
//

import UIKit

class HttpRequest: NSObject {
    static var version = "v1.0.9"
    //MARK: - get请求
    class func get(urlString: String,parameters: Dictionary<String,Any>?,success: @escaping ((_ result: [String : Any]) -> ()),failure: @escaping ((_ error: Error?) -> ())) {
        var i = 0
        var address = urlString
        if let paras = parameters {
            for (key,value) in paras {
                if i == 0 {
                    address += "?\(key)=\(value)"
                }else {
                    address += "&\(key)=\(value)"
                }
                i += 1
            }
        }
        MyLog("-----请求接口:\(urlString)-----")
        MyLog("-----请求参数:\(address)-----")
        
        let url = URL(string: address)
        var request = URLRequest(url: url!)
        request.timeoutInterval = 30
        request.httpMethod = "GET"
        //签名
        //request.addValue(getToken(), forHTTPHeaderField: "apiauth")
        //request.addValue(timestamp, forHTTPHeaderField: "timestamp")
        request.addValue(version, forHTTPHeaderField: "version")
        request.addValue("ios", forHTTPHeaderField: "apptype")
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request) { (data, respond, error) in
            if let value = data {
                MyLog(String(data: value, encoding: String.Encoding.utf8))
            }else {
                MyLog(data)
            }
            if data == nil {
                failure(error)
                return
            }
            if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : Any] {
                success(json)
            }else {
                failure(error)
            }
        }
        dataTask.resume()
    }
    ///post请求-返回json字符串
//    class func post(urlString: String,parameters: Dictionary<String,Any>?,success: @escaping ((_ result: String) -> ()),failure: @escaping ((_ error: Error?) -> ())) {
//        var i = 0
//        var address: String = ""
//        if let paras = parameters {
//            for (key,value) in paras {
//                if i == 0 {
//                    address += "\(key)=\(value)"
//                }else {
//                    address += "&\(key)=\(value)"
//                }
//                i += 1
//            }
//        }
//        MyLog("-----请求接口:\(urlString)-----")
//        MyLog("-----请求参数:\(address)-----")
//        let url = URL(string: urlString)
//        var request = URLRequest(url: url!)
//        request.timeoutInterval = 30
//        request.httpMethod = "POST"
//        request.httpBody = address.data(using: .utf8)
//        request.addValue(version, forHTTPHeaderField: "version")
//        request.addValue("ios", forHTTPHeaderField: "apptype")
//        //request.addValue("charset=UTF-8", forHTTPHeaderField: "content-type")
//        let session = URLSession.shared
//        let dataTask = session.dataTask(with: request) { (data, respond, error) in
//            if let value = data {
//                let string = String(data: value, encoding: String.Encoding.utf8) ?? "{}"
//                MyLog(string)
//                success(string)
//            }else {
//                MyLog(data)
//                failure(error)
//            }
//        }
//        dataTask.resume()
//    }
    //MARK: - post请求-针对字典参数
    class func post(urlString: String,parameters: Dictionary<String,Any>?,success: @escaping ((_ result: [String : Any]) -> ()),failure: @escaping ((_ error: Error?) -> ())) {
        var i = 0
        var address: String = ""
        if let paras = parameters {
            for (key,value) in paras {
                if i == 0 {
                    address += "\(key)=\(value)"
                }else {
                    address += "&\(key)=\(value)"
                }
                i += 1
            }
        }
        MyLog("-----请求接口:\(urlString)-----")
        MyLog("-----请求参数:\(address)-----")
        let url = URL(string: urlString)
        var request = URLRequest(url: url!)
        request.timeoutInterval = 30
        request.httpMethod = "POST"
        request.httpBody = address.data(using: .utf8)
        request.addValue(version, forHTTPHeaderField: "version")
        request.addValue("ios", forHTTPHeaderField: "apptype")
        //request.addValue("charset=UTF-8", forHTTPHeaderField: "content-type")
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request) { (data, respond, error) in
            guard let value = data else {
                failure(error)
                return
            }
            guard let json = try? (JSONSerialization.jsonObject(with: value, options: .allowFragments) as! [String : Any]) else {
                failure(error)
                return
            }
            success(json)
        }
        dataTask.resume()
    }
    //MARK: - 下载文件
    class func download(urlStr: String,success: @escaping ((_ result: Data?) -> ()),failure: @escaping ((_ error: Error) -> ())) {
        let url = URL(string: urlStr)
        var request = URLRequest(url: url!)
        request.timeoutInterval = 20
        request.httpMethod = "GET"
        request.addValue(version, forHTTPHeaderField: "version")
        request.addValue("ios", forHTTPHeaderField: "apptype")
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request) { (data, respond, error) in
            MyLog(data)
            if error == nil {
                success(data)
            }else {
                if error != nil { failure(error!) }
            }
        }
        dataTask.resume()
    }
    // MARK:- 上传图片/文件
    class func upload(urlString: String, parameters: Dictionary<String,Any>?, formData: Data, success: @escaping ((_ result: [String : Any]) -> ()), failure: @escaping ((_ error: Error?) -> ())) {
        let boundary:String="BOUNDARY"//分割标识符
        //组装body
        let body = NSMutableData()
        
        //拼接参数
        if let paras = parameters {
            for(key, value) in paras {
                body.append(NSString(format:"--\(boundary)\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
                body.append(NSString(format:"Content-Disposition:form-data;name=\"\(key)\"\r\n\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
                body.append(NSString(format:"\(value)" as NSString).data(using: String.Encoding.utf8.rawValue)!)
                body.append(NSString(format:"\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
            }
        }
        MyLog("-----请求接口:\(urlString)-----")
        MyLog("-----请求参数:\(body)-----")
        //拼接文件/图片
        body.append(formData)
        //拼接结尾
        body.append(NSString(format:"\r\n--\(boundary)--\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
        let request=NSMutableURLRequest(url:URL(string: urlString)! as URL)
        request.timeoutInterval = 30
        //设置请求方式---httpMethod
        request.httpMethod="POST"
        //上传文件必须设置---Content-Type
        let contentType:String="multipart/form-data;boundary="+boundary
        request.addValue(contentType, forHTTPHeaderField:"Content-Type")
        //设置post的请求体---httpBody
        request.httpBody = body as Data
        request.addValue(version, forHTTPHeaderField: "version")
        request.addValue("ios", forHTTPHeaderField: "apptype")
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest) { (data, respond, error) in
            if let value = data {
                MyLog(String(data: value, encoding: String.Encoding.utf8))
            }else {
                MyLog(data)
            }
            if data == nil {
                failure(error)
                return
            }
            if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : Any] {
                success(json)
            }else {
                failure(error)
            }
        }
        dataTask.resume()
    }
    //MARK: - 上传一张图片
    class func uploadOneImage(image: UIImage, success: @escaping ((_ imagePath: String) -> ()), failure: @escaping ((_ error: Error?) -> ())) {
        let boundary:String="BOUNDARY"//分割标识符
        
        let urlStr = "kUrl"+"/user/upOneImage"
        let formData = NSMutableData()
        let data = image.jpegData(compressionQuality: 1)
        formData.appendPartWithFileData(fileData: data!, name: "photo", fileName: "fileName.jpg", mimeType: "image/jpg")
        //组装body
        let body = NSMutableData()
        //拼接文件/图片
        body.append(formData as Data)
        //拼接结尾
        body.append(NSString(format:"\r\n--\(boundary)--\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
        let request=NSMutableURLRequest(url:URL(string: urlStr)! as URL)
        request.timeoutInterval = 30
        //设置请求方式---httpMethod
        request.httpMethod="POST"
        //上传文件必须设置---Content-Type
        let contentType:String="multipart/form-data;boundary="+boundary
        request.addValue(contentType, forHTTPHeaderField:"Content-Type")
        //设置post的请求体---httpBody
        request.httpBody = body as Data
        request.addValue(version, forHTTPHeaderField: "version")
        request.addValue("ios", forHTTPHeaderField: "apptype")
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest) { (data, respond, error) in
            if let value = data {
                MyLog(String(data: value, encoding: String.Encoding.utf8))
            }else {
                MyLog(data)
            }
            if data == nil {
                failure(error)
                return
            }
            if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : Any] {
                let code = ""//json.getValue("code", "")
                if code == "1" {
                    //success(json.getValue("data", ""))
                }else {
                    failure(error)
                    DispatchQueue.main.async {
                        //SwiftProgressHUD.showOnlyText(json.getValue("msg", ""))
                    }
                }
                
            }else {
                failure(error)
            }
        }
        dataTask.resume()
    }
    //MARK: - 上传一张图片
    class func uploadOneImage(image: UIImage, url: String, success: @escaping ((_ result: [String : Any]) -> ()), failure: @escaping ((_ error: Error?) -> ())) {
        let boundary:String="BOUNDARY"//分割标识符
        
        let urlStr = url
        let formData = NSMutableData()
        let data = image.jpegData(compressionQuality: 1)
        formData.appendPartWithFileData(fileData: data!, name: "photo", fileName: "fileName.jpg", mimeType: "image/jpg")
        //组装body
        let body = NSMutableData()
        //拼接文件/图片
        body.append(formData as Data)
        //拼接结尾
        body.append(NSString(format:"\r\n--\(boundary)--\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
        let request=NSMutableURLRequest(url:URL(string: urlStr)! as URL)
        request.timeoutInterval = 30
        //设置请求方式---httpMethod
        request.httpMethod="POST"
        //上传文件必须设置---Content-Type
        let contentType:String="multipart/form-data;boundary="+boundary
        request.addValue(contentType, forHTTPHeaderField:"Content-Type")
        //设置post的请求体---httpBody
        request.httpBody = body as Data
        request.addValue(version, forHTTPHeaderField: "version")
        request.addValue("ios", forHTTPHeaderField: "apptype")
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest) { (data, respond, error) in
            if let value = data {
                MyLog(String(data: value, encoding: String.Encoding.utf8))
            }else {
                MyLog(data)
            }
            if data == nil {
                failure(error)
                return
            }
            if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : Any] {
                success(json)
            }else {
                failure(error)
            }
        }
        dataTask.resume()
    }
}
extension NSMutableData {
    func appendPartWithFileData(fileData: Data, name: String, fileName: String, mimeType: String) {
        self.append(("--BOUNDARY\r\n" as String).data(using: String.Encoding.utf8)!)
        self.append(("Content-Disposition:form-data;name=\"\(name)\";filename=\"\(fileName)\"\r\n" as String).data(using: String.Encoding.utf8)!)
        self.append(("Content-Type:\(mimeType)\r\n" as String).data(using: String.Encoding.utf8)!)
        self.append(("Content-Transfer-Encoding: binary\r\n\r\n" as String).data(using: String.Encoding.utf8)!)
        self.append(fileData)
        self.append(("\r\n" as String).data(using: String.Encoding.utf8)!)
    }
}
